/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package arbre;

import fileNoeud.FilePrioriteeDeNoeud;
import fileNoeud.NoSuchElementException;
import java.util.HashMap;
import java.util.Iterator;

/**
 *
 * @author ksz
 */
public class ArbreHuffman {

    private NoeudInterne racine;
    private HashMap bitsCodeDictionnaire;

    public ArbreHuffman() {
        bitsCodeDictionnaire = new HashMap();
    }

    public ArbreHuffman(NoeudInterne racine) {
        this.racine = racine;
        bitsCodeDictionnaire = new HashMap();
    }

    public NoeudInterne getRacine() {
        return racine;
    }

    public void construireArbre(FilePrioriteeDeNoeud filePrioritee) {
        Noeud noeud1;
        Noeud noeud2;

        if (filePrioritee.estVide()) {
            System.out.println("Il n'y a aucun élément dans la file, impossible de créer l'arbre de huffman");
            return;
        }

        while (!filePrioritee.estVide()) {

            if (racine != null) {
                filePrioritee.insererPrioritee(getRacine());
            }

            try {

                noeud1 = filePrioritee.depiler();

            } catch (NoSuchElementException ex) {
                noeud1 = null;
            }

            try {

                noeud2 = filePrioritee.depiler();

            } catch (NoSuchElementException ex) {
                noeud2 = null;
            }

            racine = new NoeudInterne(noeud1, noeud2);
        }

        creerBitsCode();

    }

    public void creerBitsCode() {

        if (racine != null) {
            StringBuffer code = new StringBuffer();
            racine.creerBitsCode(code, bitsCodeDictionnaire);
        }

    }

    public void afficherBitsCode() {

        Character key;
        Iterator i = bitsCodeDictionnaire.keySet().iterator();

        while (i.hasNext())
        {
            key = (Character)i.next();
            System.out.println("Contenu arbre : " + key + " " + bitsCodeDictionnaire.get(key));
        }
    }

    public HashMap getBitsCodeDictionnaire() {
        return bitsCodeDictionnaire;
    }
}
